package cn.com.cis.utils.tree;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TreeManager {
	
	private Map<String, TreeNode> managedNodes= new HashMap<String, TreeNode>();
	
	public TreeNode findNode(String parentLongName) {
		return managedNodes.get(parentLongName);
	}
	
	public static String getNodeFullName(TreeNode node){
		
		TreeNode parentNode = null;
		String fullName = node.getNodeName();
		while ((parentNode = node.getParentNode()) != null) {
			fullName = parentNode.getNodeName() + ":" + fullName;
			node = parentNode;
		}
		
		return fullName;
	}
	
	public String getNodePermissionCode(TreeNode node){
		for(String code : managedNodes.keySet()){
			if(managedNodes.get(code) == node){
				return code;
			}
		}
		return null;
	}

	public List<TreeNode> plainTextToTree(List<String> texts){
		
		List<TreeNode> rootNodes = new ArrayList<TreeNode>();
		
		for(String text : texts){
			
			// 样例："配置管理:驱动管理:编辑数据源类型"
			String[] codes = text.split(":");
			
			int rootLevel = 0;                 // 树的跟层级
			int leafLevel = codes.length;      // 叶子节点层级，下面没有子节点
			
			String parentLongName = "";
			for(int level = 0; level < leafLevel; level++){
				
				if(0 != level){                 // 根节点没有父节点
					if(1 != level){
						parentLongName += ":";  // 只有一个父节点（非父父节点...）的情况下，拼接不能连':'
					}
					parentLongName += codes[level -1];  
				}
				
				String currentNodeFullName = "";
				if(parentLongName.length() == 0){
					currentNodeFullName = codes[level];
				} else {
					currentNodeFullName = parentLongName + ":" + codes[level];
				}
				
				if(null != findNode(currentNodeFullName)){  // 节点是否存在
					continue;
				}
				
				TreeNode currentNode = new TreeNode();
				currentNode.setNodeName(codes[level]);
				
				// 根节点
				if(level == rootLevel){
					currentNode.setRoot(true);
					rootNodes.add(currentNode);
				} 
				
				// 叶子节点
				// 根节点与叶子节点非互斥
				if (level == leafLevel - 1) {
					currentNode.setLeaf(true);
					findNode(parentLongName).addChildNode(currentNode);
				}
				
				// 中间节点
				if(level != rootLevel && level != leafLevel - 1) {
					TreeNode parentNode = findNode(parentLongName);
					
					// 双向添加
					currentNode.setParentNode(parentNode);             
					parentNode.addChildNode(currentNode);
				}
				
				// 以全路径+节点名建立快速索引
				if(level == rootLevel){
					managedNodes.put(currentNode.getNodeName(), currentNode);   // 根节点
				} else {
					managedNodes.put(parentLongName + ":" + currentNode.getNodeName(), currentNode);  // 非根节点拼接路径要连上分隔符 ':'
				}
				
			}
		}
		
		return rootNodes; //  返回根节点集合
	}
	
	public static void main(String[] args) {
		List<String> privilegeCodeString = new ArrayList<String>();
		privilegeCodeString.add("用户管理:查看用户列表");
		privilegeCodeString.add("配置管理:全局参数管理:修改参数");
		privilegeCodeString.add("配置管理:驱动管理:编辑数据源类型");
		
		System.err.println(new TreeManager().plainTextToTree(privilegeCodeString));
		System.err.println();
	}

}
